package cn.rkylin.oms.push.controller;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.item.service.IItemService;
import cn.rkylin.oms.item.vo.ItemVO;
import cn.rkylin.oms.push.adapter.PushAdapter;
import cn.rkylin.oms.push.adapter.PushAdapterFactory;
import cn.rkylin.oms.push.request.PushItemDeListing;
import cn.rkylin.oms.push.request.PushItemListing;
import cn.rkylin.oms.push.request.PushItemQuantityUpdate;
import cn.rkylin.oms.push.request.PushSkuQuantityUpdate;
import cn.rkylin.oms.system.shop.domain.Shop;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;

@Controller
@RequestMapping("/pushItem")
public class PushItemController extends ApolloController {

    private static final Log logger = LogFactory.getLog(PushItemController.class);

    @Autowired
    private LogUtil logUtil;

    @Resource(name = "redisTemplate")
    private RedisTemplate<Serializable, Serializable> redisTemplate;

    /**
     * 店铺服务层
     */
    @Autowired
    private IShopService shopService;
    @Autowired
    private IItemService itemService;

    /**
     * 商品上架接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushItemListing", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushItemListing(@RequestBody PushItemListing request) throws Exception {

        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcItemCode());

            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushItemListing(shop, request.getEcItemCode(), request.getStockCount());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 商品下架接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushItemDeListing", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushItemDeListing(@RequestBody PushItemDeListing request) throws Exception {

        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcItemCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }

            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");
            resultMap = pushAdapter.pushItemDeListing(shop, request.getEcItemCode());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 同步商品库存接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushItemQuantityUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushItemQuantityUpdate(@RequestBody PushItemQuantityUpdate request) throws Exception {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcItemCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushItemQuantityUpdate(shop, request.getEcItemCode(), request.getSkuId(), request.getNum());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 同步商品规格库存接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushSkuQuantityUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushSkuQuantityUpdate(@RequestBody PushSkuQuantityUpdate request) throws Exception {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcItemCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushSkuQuantityUpdate(shop, request.getEcItemCode(), request.getEcSkuCode(), request.getNum());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 请求参数验证
     * 
     * @throws Exception
     */
    private Map<String, Object> pushDataValidate(String shopId, String ecItemCode) throws Exception {

        Map<String, Object> resultMap = new HashMap<>();

        // shopId 没有的场合
        if (StringUtils.isEmpty(shopId)) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺不存在");
            return resultMap;
        }
        // ecItemCode 没有的场合
        if (StringUtils.isEmpty(ecItemCode)) {
            resultMap.put("success", "n");
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }

        Shop shop = getShop(shopId);
        if (shop == null || StringUtils.isEmpty(shop.getEnable()) || StringUtils.isEmpty(shop.getDeleted())) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺不存在");
            return resultMap;
        } else if (shop.getEnable().equalsIgnoreCase("n")) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺未启用");
            return resultMap;
        } else if (shop.getDeleted().equalsIgnoreCase("y")) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺已删除");
            return resultMap;
        }

        // 如果是子店铺
        if (StringUtils.isNotEmpty(shop.getParentShop())) {
            Shop shopParent = getShop(shop.getParentShop());
            shop.setApiUrl(shopParent.getApiUrl());
            shop.setAppKey(shopParent.getAppKey());
            shop.setAppSecret(shopParent.getAppSecret());
            shop.setSessionKey(shopParent.getSessionKey());
        }

        // // 根据ecItemCode取得ecitem的主键
        // List<String> listEcItem = getEcItem(shopId, ecItemCode);
        // if (listEcItem == null || listEcItem.size() <= 0) {
        // resultMap.put("success", "n");
        // resultMap.put("msg", "数据不存在");
        // return resultMap;
        // }

        resultMap.put("shop", shop);
        PushAdapter pushAdapter = PushAdapterFactory.getPushAdapter(shop);
        if (pushAdapter == null) {
            resultMap.put("success", "n");
            resultMap.put("msg", "推送失败");
            return resultMap;
        }
        resultMap.put("pushAdapter", pushAdapter);
        return resultMap;
    }

    private String getShopIdByItem(List<String> listEcItem) {
        String shopId = "";
        try {

            // for (int i = 0; i < listEcItem.size(); i++) {
            // ItemVO itemVo = itemService.getEcItemById(listEcItem.get(i));
            // shopId = itemVo.getShopId();
            // break;
            // }

            if (listEcItem.size() > 0) {
                ItemVO itemVo = itemService.getEcItemById(listEcItem.get(0));
                shopId = itemVo.getShopId();
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return shopId;
    }

    /**
     * 根据shopId取得shop对象
     * 
     * @param shopid
     * @return
     */

    private ShopVO getShop(String shopid) {
        ShopVO shopVO = null;
        try {
            if (StringUtils.isNotBlank(shopid)) {
                shopVO = shopService.getShopById(shopid);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            shopVO = null;
        }
        return shopVO;
    }

    // /**
    // * 根据ecItemCode取得EcItem对象
    // *
    // * @param ecItemCode
    // * @return
    // */
    //
    // private List<String> getEcItem(String shopId, String ecItemCode) {
    // List<String> listEcItem = new ArrayList<String>();
    //
    // try {
    // ItemVO parameter = new ItemVO();
    // ItemVO itemVo = null;
    // parameter.setShopId(shopId);
    // parameter.setEcItemCode(ecItemCode);
    // List<ItemVO> list = itemService.findByItemCode(parameter);
    // if (list != null) {
    // for (int i = 0; i < list.size(); i++) {
    // itemVo = list.get(i);
    // listEcItem.add(itemVo.getEcItemId());
    // }
    // }
    // } catch (Exception ex) {
    // logger.error(ex.getMessage(), ex);
    // listEcItem = null;
    // }
    // return listEcItem;
    // }

}
